#!/bin/bash

pub=/srv/msys2repo
staging=/home/repo/staging

SIGNWITHKEY=()
if [[ -n $GPGKEY ]]; then
    SIGNWITHKEY=(-u "${GPGKEY}")
fi

gpg --detach-sign "${SIGNWITHKEY[@]}" "${0}" || exit 1
rm "${0}.sig"

(
    shopt -s nullglob
    for f in "${staging}"/*/*/*.{pkg,src}.tar.{gz,xz,zst}
    do
        test -f "$f.sig" || gpg --detach-sign "${SIGNWITHKEY[@]}" "$f" || exit 1
    done
)

update_packages() {
    local repo="${1}"
    shift
    local path="${1}"
    shift
    local srcpath="${1}"
    shift

    local files=( $(find "${staging}/${path}" -name "*.pkg.tar.*" -not -name "*.sig") )
    if [ "${#files[@]}" -gt 0 ]
    then
        echo "==> ${path}"
        cp "${pub}/${path}/${repo}".{db,files}{,.tar.gz}{,.sig} "${staging}/${path}/"
        repo-add -n -p -s -v "${staging}/${path}/${repo}.db.tar.gz" "${files[@]}" || exit 1
#        chmod 0640 "${staging}/${path}"/*
        mv "${staging}/${path}"/* "${pub}/${path}/"

        inrepo="$(bsdtar -xOf "${pub}/${path}/${repo}.db.tar.gz" "*/desc" | grep -A 1 %FILENAME% | sed -e '/^%FILENAME%$/d' -e '/^--$/d' | sed -r 's/^(.*)$/\1\n\1.sig/' | sort)"
        infs="$(find "${pub}/${path}" -name "*.pkg.tar.*" -printf '%f\n' | sort)"
        for f in $(echo "${inrepo}" | grep -vxF -f <(echo "${infs}"))
        do
            echo "==> WARNING: '${f}' is missing."
        done
        inrepo="$(bsdtar -xOf "${pub}/${path}/${repo}.db.tar.gz" "*/desc" | grep -A 4 -e %BASE% | awk '/^%BASE%$/ { getline; printf "%s-", $0; getline; getline; getline; printf "%s.src.tar.gz\n", $0 }' | sed -r 's/^(.*)$/\1\n\1.sig/' | sort | uniq)"
        infs="$(find "${pub}/${srcpath}" -name "*.src.tar.*" -printf '%f\n' | sort)"
        for f in $(echo "${inrepo}" | grep -vxF -f <(echo "${infs}"))
        do
            echo "==> WARNING: '${f}' is missing."
        done
        echo
    fi
}

update_sources() {
    local path="${1}"
    shift

    if [ -n "$(find "${staging}/${path}/sources" -name "*.src.tar.*")" ]
    then
        echo "==> ${path}"
        mv "${staging}/${path}/sources"/* "${pub}/${path}/sources/"
    fi
}

update_sources mingw
update_sources msys

update_packages mingw64 "mingw/x86_64" "mingw/sources"
update_packages mingw32 "mingw/i686"   "mingw/sources"
update_packages ucrt64  "mingw/ucrt64" "mingw/sources"
update_packages msys    "msys/x86_64"  "msys/sources"
update_packages msys    "msys/i686"    "msys/sources"
